/*
 * 文件名： MerchantServerRes.java
 * 
 * 工程名称: bis-web
 *
 * Gopay
 *
 * 创建日期： 2018年1月10日
 *
 * Copyright(C) 2018, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.web.controller.merchant;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gopay.common.constants.bank.PabConstants;
import com.gopay.common.domain.bank.merchant.MerchantSettledMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.FastJsonUtil;
import com.gopay.common.util.HttpTransport;
import com.gopay.remote.bank.businesses.MerchantSettledService;

/**
 * 商户入驻异步通知
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2018年1月10日
 */
@Controller
public class MerchantServerRes {
	/**
	 * 定义日志对象
	 */
	private static Log logger = LogFactory.getLog(MerchantServerRes.class);

	@Resource(name = "merSettledPabServiceClient")
	private MerchantSettledService merSettledPabServiceClient;
	@Resource(name = "notifyConsolePab")
	private HttpTransport notifyConsolePab;

	@RequestMapping(value = "/merchantServerRes")
	protected void execute(HttpServletRequest request, HttpServletResponse response) {
		logger.error("---------------merchantServerRes  start ---------------");

		TreeMap<String, String> params = new TreeMap<String, String>();
		Map<String, String> submitParam = new HashMap<String, String>();
		MerchantSettledMessage message = new MerchantSettledMessage();
		String returnNo=null;
		String returnType=null;
		/**
		 * 打印请求参数,并封装到map中
		 */
		params = displayRequestParameters(request, logger, params);
		message.setPlainMessage(FastJsonUtil.collectToString(params));
		/**
		 * 解密并且验签
		 */
		try {
			if ((Boolean) merSettledPabServiceClient.verify(message)) {
				if (PabConstants.MERCHANT_NOTIFY.equals(params.get("trade_type"))) {
					returnNo=params.get("mct_no");
					returnType=PabConstants.MERCHANT_NOTIFY;
				}else if(PabConstants.SHOP_NOTIFY.equals(params.get("trade_type"))){
					returnNo=params.get("shop_no");
					returnType=PabConstants.SHOP_NOTIFY;
				}else if(PabConstants.CONTRACT_NOTIFY.equals(params.get("trade_type"))){
					returnNo=params.get("ctt_id");
					returnType=PabConstants.CONTRACT_NOTIFY;
				}
				submitParam=buildSubmitParam(submitParam,params,returnNo,returnType);
			} else {
				submitParam.put("orderStatus", "E");
				submitParam.put("returnMsg", "验签失败");
			}
			/**
			 * 通知console
			 */
			notifyConsolePab.submit(submitParam);
			/**
			 * 通知银行
			 */
			notifyBank(response);
		} catch (GopayException e) {
			logger.error("messageverify error：", e);
		} catch (Exception e) {
			logger.error("BankResBase error：", e);
		}
	}

	/**
	 * 
	 * 功能描述：输出异步通知请求参数，商户入驻支付返回的request获取输入流，然后输出通知参数
	 *
	 * @param request
	 * @param logger
	 * 
	 * @author 宣广海
	 *
	 * @since 2016年8月9日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@SuppressWarnings("rawtypes")
	private TreeMap<String, String> displayRequestParameters(HttpServletRequest request, Log logger,
			TreeMap<String, String> params) {
		for (Enumeration enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
			String eleName = (String) enumeration.nextElement();
			String eleValue = request.getParameter(eleName);
			if (logger != null) {
				logger.error("map key: [" + eleName + "]，value: [" + eleValue + "]");
			}
			params.put(eleName, eleValue);
		}
		return params;
	}

	private boolean notifyBank(HttpServletResponse response) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			// 通知银行成功接收银行通知
			String notifyMsg = "notify_success";
			logger.info("notifyBank send content: \n[" + notifyMsg + "]");
			response.setContentLength(notifyMsg.getBytes().length);
			response.getOutputStream().write(notifyMsg.getBytes());
			response.getOutputStream().close();
			return true;
		} catch (IOException e) {
			logger.info(e.getMessage());
		}
		return true;
	}
	private Map<String, String> buildSubmitParam(Map<String, String> submitParam,TreeMap<String, String> params,String returnNo,String returnType){
		if(StringUtils.isNotBlank(returnNo)&&StringUtils.isNotBlank(returnType)){
			submitParam.put("returnNo", returnNo);
			submitParam.put("returnType", returnType);
			// 商户状态（0未审核，1已审核，2审核未通过，3待审核，4已删除，5初审通过）
			submitParam.put("status", params.get("status"));
			submitParam.put("remark", params.get("remark"));
			submitParam.put("upd_time", params.get("upd_time"));
			submitParam.put("orderStatus", "S");
			submitParam.put("returnMsg", "验签通过");
		}else{
			submitParam.put("orderStatus", "E");
			submitParam.put("returnMsg", "返回类型不符合进件类型！");
		}	
		return submitParam;
	}
}
